#region File Header
//-----------------------------------------------------------------------------
// SibLib
//
// Copyright (C) 2010 Julien Villers
// This program is distributed under the terms of the 
// GNU Lesser General Public License (LGPL).
// See Docs/lgpl.txt and Docs/gpl.txt
//
// This file is based on GameStateManagement sample (C) Microsoft.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SibLib.Sound;
#endregion

namespace SibLib.GameState
{
    /// <summary>
    /// Base class for screens that contain a menu of options. The user can
    /// move up and down to select an entry, or cancel to back out of the screen.
    /// </summary>
    public abstract class MenuScreen : GameScreen
    {
        #region Fields

        private List<MenuEntry> m_MenuEntries;
        protected int m_SelectedEntry = 0;
        protected string m_MenuTitle;
        /// <summary>
        /// This becomes valid after the LoadContent method for MenuScreen has been called.
        /// </summary>
        protected ISoundManager m_SoundManager;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the list of menu entries, so derived classes can add
        /// or change the menu contents.
        /// </summary>
        protected virtual internal IList<MenuEntry> MenuEntries
        {
            get { return m_MenuEntries; }
        }

        public string CueNameUpDown
        {
            get;
            set;
        }

        public string CueNameValid
        {
            get;
            set;
        }

        public string CueNameCancel
        {
            get;
            set;
        }

        #endregion

        #region Initialization

        /// <summary>
        /// Constructor.
        /// </summary>
        public MenuScreen(string menuTitle)
        {
            this.m_MenuTitle = menuTitle;
            m_MenuEntries = new List<MenuEntry>();

            TransitionOnTime = TimeSpan.FromSeconds(1.0f);
            TransitionOffTime = TimeSpan.FromSeconds(0.7f);
        }

        public override void LoadContent()
        {
            base.LoadContent();

            m_SoundManager = (ISoundManager)ScreenManager.Game.Services.GetService(typeof(ISoundManager));
        }

        #endregion

        #region Handle Input

        /// <summary>
        /// Responds to user input, changing the selected entry and accepting
        /// or cancelling the menu.
        /// </summary>
        public override void HandleInput(GameTime gameTime, InputState input)
        {
            // Move to the previous menu entry?
            if (input.IsMenuUp(ControllingPlayer))
            {
                OnSelectionChange(m_SelectedEntry - 1);

                PlaySound(CueNameUpDown);
            }

            // Move to the next menu entry?
            if (input.IsMenuDown(ControllingPlayer))
            {
                OnSelectionChange(m_SelectedEntry + 1);

                PlaySound(CueNameUpDown);
            }

            // Accept or cancel the menu? We pass in our ControllingPlayer, which may
            // either be null (to accept input from any player) or a specific index.
            // If we pass a null controlling player, the InputState helper returns to
            // us which player actually provided the input. We pass that through to
            // OnSelectEntry and OnCancel, so they can tell which player triggered them.
            PlayerIndex playerIndex;

            if (input.IsMenuSelect(ControllingPlayer, out playerIndex))
            {
                OnSelectEntry(m_SelectedEntry, playerIndex);
                PlaySound(CueNameValid);
            }
            else if (input.IsMenuCancel(ControllingPlayer, out playerIndex))
            {
                OnCancel(playerIndex);
                PlaySound(CueNameCancel);
            }

            if (ControllingPlayer.HasValue)
                OnCustomInput(input);
        }

        protected virtual void OnSelectionChange(int newSelection)
        {
            if (newSelection < 0)
                newSelection = m_MenuEntries.Count - 1;

            if (newSelection >= m_MenuEntries.Count)
                newSelection = 0;

            m_SelectedEntry = newSelection;
        }

        /// <summary>
        /// Handler for when the user has chosen a menu entry.
        /// </summary>
        protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex)
        {
            m_MenuEntries[entryIndex].OnSelectEntry(playerIndex);
        }

        /// <summary>
        /// Handler for when the user has cancelled the menu.
        /// </summary>
        protected virtual void OnCancel(PlayerIndex playerIndex)
        {
            ExitScreen();
        }

        /// <summary>
        /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
        /// </summary>
        protected void OnCancel(object sender, PlayerIndexEventArgs e)
        {
            OnCancel(e.PlayerIndex);
        }

        protected void OnCustomInput(InputState inputState)
        {
            m_MenuEntries[m_SelectedEntry].OnCustomInput(inputState, ControllingPlayer.Value);
        }

        #endregion

        #region Sound Helper
        protected void PlaySound(string cueName)
        {
            if (m_SoundManager == null)
                return;

            if (cueName == null)
                return;

            m_SoundManager.Play(cueName);
        }

        /// <summary>
        /// This helper copies this screens cue names to another screen.
        /// </summary>
        /// <param name="screen">Target screen to setup</param>
        protected void CopyCueNamesTo(MenuScreen screen)
        {
            screen.CueNameCancel = CueNameCancel;
            screen.CueNameUpDown = CueNameUpDown;
            screen.CueNameValid = CueNameValid;
        }
        #endregion

        #region Update and Draw

        /// <summary>
        /// Updates the menu.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            // Update each nested MenuEntry object.
            for (int i = 0; i < m_MenuEntries.Count; i++)
            {
                bool isSelected = IsActive && (i == m_SelectedEntry);

                m_MenuEntries[i].Update(this, isSelected, gameTime);
            }
        }

        /// <summary>
        /// Draws the menu.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
            SpriteFont font = ScreenManager.Font;

            Vector2 position = new Vector2(128, 150);

            // Make the menu slide into place during transitions, using a
            // power curve to make things look more interesting (this makes
            // the movement slow down as it nears the end).
            float transitionOffset = (float)Math.Pow(TransitionPosition, 2);

            if (ScreenState == ScreenState.TransitionOn)
                position.X -= transitionOffset * 256;
            else
                position.X += transitionOffset * 512;

            spriteBatch.Begin();

            // Draw each menu entry in turn.
            for (int i = 0; i < m_MenuEntries.Count; i++)
            {
                MenuEntry menuEntry = m_MenuEntries[i];

                bool isSelected = IsActive && (i == m_SelectedEntry);

                menuEntry.Draw(this, position, isSelected, gameTime);

                position.Y += menuEntry.GetHeight(this);
            }

            // Draw the menu title.
            Vector2 titlePosition = new Vector2(426, 72);
            Vector2 titleOrigin = font.MeasureString(m_MenuTitle) / 2;
            Color titleColor = new Color(192, 192, 192, TransitionAlpha);
            float titleScale = 1.25f;

            titlePosition.Y -= transitionOffset * 100;

            spriteBatch.DrawString(font, m_MenuTitle, titlePosition, titleColor, 0,
                                   titleOrigin, titleScale, SpriteEffects.None, 0);

            spriteBatch.End();
        }


        #endregion
    }
}
